package main

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	tcr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tcr/v20190924"
)

func main() {
	credential := common.NewCredential(
		"AKIDoV2LRO7jHmDYlpndJpBf1KUQ9mBLZaQ7",
		"fAXnuoY7bu78vY1JVQCY7jU8ZorklfXM",
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "tcr.tencentcloudapi.com"
	client, _ := tcr.NewClient(credential, "ap-guangzhou", cpf)
	request := tcr.NewDescribeImagePersonalRequest()

	aliYunVpcImageName := "ccr.ccs.tencentyun.com/wenwo/wenwo-cloud-core-domain-doctor-service-provider:1.0.0-SNAPSHOT-master-3563-2b9e130a70"
	parts := strings.SplitN(aliYunVpcImageName, "/", 2)

	if len(parts) < 2 {
		fmt.Println("Invalid image name format")
		return
	}

	pathAndTag := parts[1]

	pathAndTagParts := strings.SplitN(pathAndTag, ":", 2)

	var path, tag string
	if len(pathAndTagParts) == 2 {
		path = pathAndTagParts[0]
		tag = pathAndTagParts[1]
	} else {
		path = pathAndTagParts[0]
		tag = ""
	}

	request.RepoName = common.StringPtr(path)
	response, err := client.DescribeImagePersonal(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}

	// 解析JSON响应
	var respData map[string]interface{}
	err = json.Unmarshal([]byte(response.ToJsonString()), &respData)
	if err != nil {
		fmt.Printf("Error parsing JSON response: %s", err)
		return
	}

	// 检查Tag是否存在
	tagFound := false
	if response, ok := respData["Response"].(map[string]interface{}); ok {
		if data, ok := response["Data"].(map[string]interface{}); ok {
			if tagInfo, ok := data["TagInfo"].([]interface{}); ok {
				for _, tagInfoItem := range tagInfo {
					if tagInfoMap, ok := tagInfoItem.(map[string]interface{}); ok {
						if tagName, ok := tagInfoMap["TagName"].(string); ok && tagName == tag {
							tagFound = true
							break
						}
					}
				}
			}
		}
	}

	fmt.Println("标签：", tag)

	if tagFound {
		fmt.Println("镜像存在")
	} else {
		fmt.Println("镜像不存在")
	}
}
